var rendererOptions = {
	draggable : true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();

var map;

var isPollutionShowing;
var pollutionGrid;
var city = new google.maps.LatLng(55.9410655, -3.2053836);
var currentSubstance = "";
var GridColorMap = {};

function loadToolsAndMap() {
	var mapOptions = {
		zoom : 12,
		center : city
	};
	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById('directionsPanel'));

	google.maps.event.addListener(directionsDisplay, 'directions_changed',
			function() {
				computeTotalDistance(directionsDisplay.getDirections());
			});

	var menuButtons = document.querySelector("#menu-buttons");
	menuButtons.className = "btn-group";
	map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(menuButtons);

	var menuButtonsMap = document.querySelector("#menu-buttons-map");
	menuButtonsMap.className = "btn-group";
	map.controls[google.maps.ControlPosition.TOP_CENTER].push(menuButtonsMap);

	var autocomplete1 = new google.maps.places.Autocomplete(document
			.querySelector("#start-from"));
	var autocomplete2 = new google.maps.places.Autocomplete(document
			.querySelector("#destination"));

}
function initialize() {
	loadToolsAndMap();
	addButtonListeners();
	// calcRoute("The University of Edinburgh, South Bridge, Edinburgh, United
	// Kingdom", "Edinburgh Airport, Edinburgh, United Kingdom", "DRIVING");
}

function addButtonListeners() {
	$("#show-directions-pollution-button").click(function() {
		drawPolyLines();
	});
	$("#find-route-button").click(function() {
		$('#find-route-model').modal();

	});

	$("#show-directions-button").click(function() {
		$('#show-directions-model').modal();
	});

	$("#find-route-ok").click(
			function() {
				hidePollution(true);
				setTimeout(function() {
					calcRoute($("#start-from").val(), $("#destination").val(),
							$("#travel-mode").val());
				}, 0);
			});

	$("#show-pollution-button").click(showPollution);

}

function hidePollution(destroyGridObject) {
	isPollutionShowing = false;
	if (pollutionGrid) {
		for (var i = 0; i < pollutionGrid.length; i++) {
			pollutionGrid[i].setMap(null);
		}
	}
	if (destroyGridObject) {
		pollutionGrid = null;
	}
}

function showPollution() {
	if (!isPollutionShowing) {
		isPollutionShowing = true;
		if (!pollutionGrid) {
			// get Pollution Data
			var bounds = map.getBounds();
			$.ajax({
				type : "GET",
				url : "data",
				dataType : "json",
				data : {
					southwest : bounds.getSouthWest().toString(),
					northeast : bounds.getNorthEast().toString(),
					grids : true,
					current : true
				}
			}).done(function(json) {
				if (json.observations.length === 0)
					alert("No Observation");
				console.log(json);
				createPollutionGrid(json);
			});
		} else {
			for (var i = 0; i < pollutionGrid.length; i++) {
				pollutionGrid[i].setMap(map);
			}
		}
	} else {
		hidePollution();
	}
}

function getGridId(lat, lng) {
	var lat = parseInt(lat * 100) / 100;
	var lng = parseInt(lng * 100) / 100;
	return lat + "#" + lng;
}

function createPollutionGrid(json) {
	pollutionGrid = [];
	GridColorMap = {};
	for (var i = 0; i < json.observations.length; i++) {
		var o = json.observations[i];
		var color = aqiColor(o);
		GridColorMap[getGridId(o.latitude, o.longitude)] = aqiColor(o);
		pollutionGrid.push(new google.maps.Rectangle({
			strokeColor : color,
			strokeOpacity : 0.8,
			strokeWeight : 1,
			fillColor : color,
			fillOpacity : 0.35,
			map : map,
			// bounds: map.getBounds()
			bounds : new google.maps.LatLngBounds(new google.maps.LatLng(
					o.latitude, o.longitude), new google.maps.LatLng(o.latitude
					+ json.gridSize, o.longitude + json.gridSize))
		}));

	}
	// for (var lat = json.southWest.latitude; lat < json.northEast.latitude;
	// lat += json.gridSize) {
	// for (var lng = json.southWest.longitude; lng < json.northEast.longitude;
	// lng += json.gridSize) {
	// pollutionGrid.push(new google.maps.Rectangle({
	// strokeColor : '#FF0000',
	// strokeOpacity : 0.8,
	// strokeWeight : 0,
	// fillColor : '#FF0000',
	// fillOpacity : 0.35,
	// map : map,
	// // bounds: map.getBounds()
	// bounds : new google.maps.LatLngBounds(new google.maps.LatLng(
	// lat, lng), new google.maps.LatLng(lat + json.gridSize,
	// lng + json.gridSize))
	// }));
	// }
	// }
}
function calcRoute(origin, destination, travelMode) {
	var request = {
		origin : origin,
		destination : destination,
		travelMode : travelMode || google.maps.TravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			// hidePollution();
			directionsDisplay.setDirections(response);
		}
	});
}

function computeTotalDistance(result) {
	var total = 0;
	var myroute = result.routes[0];
	for (var i = 0; i < myroute.legs.length; i++) {
		total += myroute.legs[i].distance.value;
	}
	total = total / 1000.0;
	document.getElementById('total-distance').innerHTML = total + ' km';
}

google.maps.event.addDomListener(window, 'load', initialize);

// make markers
function m(map, coords) {
	var marker = new google.maps.Marker({
		position : coords,
		map : map,
		title : coords.toString()
	});
}

// google.maps.event.addDomListener(window, 'load', initialize);

var colors = [ "rgba(156, 255, 156, 0.6)", "rgba(49, 255, 0, 0.6)",
		"rgba(49, 207, 0, 0.6)", "rgba(255, 255, 0, 0.6)",
		"rgba(255, 207, 0, 0.6)", "rgba(255, 154, 0, 0.6)",
		"rgba(255, 100, 100, 0.6)", "rgba(255, 0, 0, 0.6)",
		"rgba(153, 0, 0, 0.6)", "rgba(206, 48, 255, 0.6)" ];

var pathColors = [ "rgba(156, 255, 156, 1)", "rgba(49, 255, 0, 1)",
		"rgba(49, 207, 0, 1)", "rgba(255, 255, 0, 1)", "rgba(255, 207, 0, 1)",
		"rgba(255, 154, 0, 1)", "rgba(255, 100, 100, 1)", "rgba(255, 0, 0, 1)",
		"rgba(153, 0, 0, 1)", "rgba(206, 48, 255, 1)" ];

function getPollutionLevel(value, substance) {
	var boundaries = [];
	switch (substance) {
	case "o3":
		boundaries = [ 0, 34, 67, 101, 121, 141, 161, 188, 214, 241 ];
		break;
	case "no2":
		boundaries = [ 0, 68, 135, 201, 268, 335, 401, 468, 535, 601 ];
		break;
	case "so2":
		boundaries = [ 0, 89, 178, 267, 355, 444, 533, 711, 888, 1065 ];
		break;
	case "pm2p5":
		boundaries = [ 0, 12, 24, 36 - 41, 42, 48, 54, 59, 65, 71 ];
		break;
	case "pm10":
		boundaries = [ 0, 17, 34, 51, 59, 67, 76, 84, 92, 101 ];
		break;
	default:
		return -1;
	}
	var i = 0;
	for (; i < boundaries.length; i++) {
		if (value < boundaries[i]) {
			break;
		}
	}
	return i - 1;
}

function getClass(value, substance) {
	var classNames = [ "low-1", "low-2", "low-3", "moderate-1", "moderate-2",
			"moderate-3", "high-1", "high-2", "high-3", "very-high" ];
	var level = getPollutionLevel(value, substance);
	if (level == -1)
		return "na";
	return classNames[level];
}

function aqiColor(o, customColors) {
	var substance_list = [ "no2", "pm10", "so2", "o3", "pm2p5" ];
	var max = -1;
	maxS = "";
	for (var i = 0; i < substance_list.length; i++) {
		var level = getPollutionLevel(o[substance_list[i]], substance_list[i]);
		if (level > max) {
			max = level;
			maxS = substance_list[i];
		}
	}
	return (customColors || colors)[max];
}

var lastColor = "#00ff00";
var grid = null;

function getPathColor(path) {
	var gid = getGridId(path[i].lat(), path[i].lng());
	if (gid != grid) {
		grid = gid;
		return "#00ff00" === lastColor ? "#0000ff" : "#00ff00";
	}
	return lastColor;
}

function printListOfBoxesInvolved(path) {
	var grid = {};
	for (var i = 0; i < path.length; i++) {
		var gid = getGridId(path[i].lat(), path[i].lng());
		if (!grid[gid]) {
			grid[gid] = 0;
		}
		grid[gid]++;
	}
	GridColorMap = {};
	var count = 0;

	for ( var i in grid) {
		GridColorMap[i] = count++;
	}
	console.log(GridColorMap);
	return GridColorMap;
}

function printListOfBoxesInvolvedArray(path) {
	var grid = [];
	for (var i = 0; i < path.length; i++) {
		var gid = getGridId(path[i].lat(), path[i].lng());
		grid.push(gid);
	}
	console.log(grid);
}

var Colors = [ "#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#000000",
		"#FFFF00", "#00FFFF", "#FF00FF" ];

function getColor(path, i) {
	return pathColors[GridColorMap[getGridId(path.lat(), path.lng())] % 10];
}

function drawPolyLines() {
	var steps = directionsDisplay.directions.routes[0].legs[0].steps;
	var path = [];
	for (var i = 0; i < steps.length; i++) {
		for (var j = 0; j < steps[i].path.length; j++) {
			path.push(steps[i].path[j]);
		}
	}
	console.info(path.length);
	// path = [ path[0], path[1], path[2], path[3] ];
	path = new Line().getAllBreakLatLng(path);
	console.warn(path.length);
	printListOfBoxesInvolved(path);
	// printListOfBoxesInvolvedArray(path);

	for (var i = 0; i < path.length - 1; i++) {
		var p = new google.maps.Polyline({
			path : [ path[i], path[i + 1] ],
			geodesic : true,
			strokeColor : getColor(path[i], i),
			strokeOpacity : 1.0,
			strokeWeight : 5
		});
		p.setMap(map);
	}
}

/** ************** */
